package com.david.core.utils;


import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * 使用时先调用： ToastUtils.instance.init(applicationContext)初始化
 * */
public class ToastUtilsJava {
    private FrameLayout view;
    private TextView tv;
    private Toast toast;

    private static ToastUtils instance = new ToastUtils();

    private ToastUtilsJava(){

    }

    public static ToastUtils getInstance() {
        return instance;
    }

    /**
     * 初始化Toast
     * @param context
     */
    public void init(Context context) throws Exception {
        if (context == null) {
            throw new Exception("context for init must not be null");
        }
        view = new FrameLayout(context);
        view.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        tv = new TextView(context);
        tv.setTextSize(16f);
        tv.setTextColor(Color.parseColor("#3e3a39"));
        view.addView(tv);
        toast = new Toast(context);
        toast.setView(view);

        toast.setGravity(Gravity.CENTER, 0, 0);

    }

    /**
     * 显示Toast
     * @param content 内容
     * @param duration Toast持续时间
     */
    private void display(CharSequence content, int duration) {
        if (!TextUtils.isEmpty(content)) {
            tv.setText(content);
            toast.setDuration(duration);
            toast.show();
        }
    }


    /**
     * 显示toast
     * @param content  内容
     * @param duration  持续时间
     */
    public void toast(String content, int duration) {
        if (!TextUtils.isEmpty(content)) {
            display(content, duration);
        }
    }

    /**
     * 显示默认持续时间为short的Toast
     * @param content  内容
     */
    public void toast(String content) {
        toast(content, Toast.LENGTH_SHORT);
    }

    public void toastLong(String content){
        toast(content, Toast.LENGTH_LONG);
    }

    public Boolean isInited(){
        return tv != null;
    }
}